package com.wantong.voice.webrtc;

import cn.hutool.core.io.FileUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;

/**
 * VoiceUtils 工具入口
 *
 * @author : stan
 * @version : 1.0
 * @date :  2021/10/13 12:28 上午
 **/
public class VoiceUtils {

    /**
     * 音频噪声和增益处理
     * @param origin raw audio
     * @return
     */
    public static byte[] nsAndAgc(byte[] origin) {
        //噪声参数
        NoiseSuppressorUtils nsUtils = new NoiseSuppressorUtils();
        long nsxId = nsUtils.nsxCreate();
        int nsxInit = nsUtils.nsxInit(nsxId, 16000);
        int nexSetPolicy = nsUtils.nsxSetPolicy(nsxId, 2);
        System.out.println("nsxId: " + nsxId + "    nsxInit:" + nsxInit + " nexSetPolicy:" + nexSetPolicy);

        //增益参数
        AutomaticGainControlUtils agcUtils = new AutomaticGainControlUtils();
        long agcId = agcUtils.agcCreate();
        int agcInitResult = agcUtils.agcInit(agcId, 0, 255, 3, 16000);
        int agcSetConfigResult = agcUtils.agcSetConfig(agcId, (short) 12, (short) 12, true);
        System.out.println("agcId: " + agcId + "    agcInitResult:" + agcInitResult + " agcSetConfigResult:" + agcSetConfigResult);
        ByteBuffer buffer = ByteBuffer.wrap(origin);

        //  loop 每次处理不超过10ms
        //预留最后长度
        ByteBuffer out = ByteBuffer.allocate(origin.length + 320);
        ShortBuffer sout = out.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
        while (buffer.hasRemaining()) {
            System.out.println("开始读出处理:");
            byte[] tempbytes = new byte[320];
            buffer.get(tempbytes, 0, Math.min(buffer.remaining(), 320));
            short[] tarShortArr = new short[160];
            short[] outNsData = new short[160];
            short[] outAgcData = new short[160];
            ByteBuffer.wrap(tempbytes).order(ByteOrder.LITTLE_ENDIAN)
                    .asShortBuffer()
                    .get(tarShortArr);
            nsUtils.nsxProcess(nsxId, tarShortArr, 1, outNsData);
            agcUtils.agcProcess(
                    agcId, outNsData, 1, 160, outAgcData,
                    0, 0, 0, false
            );
            System.out.println("写出数据:" + outAgcData.length);
            sout.put(outAgcData);
            System.out.println("写出完成");
        }
        System.out.println("end loop");
        //    end loop
        nsUtils.nsxFree(nsxId);
        agcUtils.agcFree(agcId);
        System.out.println("end free");
        System.out.println("写出文件:" + out.remaining());
        //写出文件
        out.rewind();
        byte[] target = new byte[out.remaining()];
        out.get(target, 0, target.length);

        return target;
    }
}
